package com.ease.web.server;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ServerHostDetector {

	private static final transient Log log = LogFactory.getLog(ServerHostDetector.class);

	public static String getHostName() {
		String hostName = null;
		try {
			List<String> lines = IOUtils.readLines(Runtime.getRuntime().exec(isWindows() ? "cmd.exe /c \"set computername\"" : "hostname").getInputStream());
			if (CollectionUtils.isNotEmpty(lines) && StringUtils.isNotBlank(lines.get(0))) {
				hostName = lines.get(0);

				if (hostName.indexOf('=') > 0) {
					hostName = hostName.substring(hostName.indexOf('=') + 1);
				}
			}
		} catch (Throwable ex) {
			log.error("获取机器名失败！", ex);
		}

		return hostName;
	}

	private static boolean isWindows() {
		return StringUtils.containsIgnoreCase(System.getProperty("os.name"), "Windows");
	}

	public static String getIp() {
		try {
			Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
			while (nis.hasMoreElements()) {
				NetworkInterface ni = nis.nextElement();
				if (!ni.isUp())
					continue;
				if (ni.isLoopback())
					continue;
				if (ni.isPointToPoint())
					continue;
				if (ni.isVirtual())
					continue;

				Enumeration<InetAddress> ias = ni.getInetAddresses();
				while (ias.hasMoreElements()) {
					InetAddress ia = ias.nextElement();
					if (ia instanceof Inet4Address) {
						return ia.getHostAddress();
					}
				}
			}
		} catch (Exception ex) {
			log.error("获取IP失败！", ex);
		}

		return null;
	}

	public static void main(String[] args) {
		System.out.println(getIp());
		System.out.println(getHostName());
	}

}
